package iha.auh.kds.aba.painratingapp;

import java.text.DecimalFormat;
import java.util.Arrays;

import com.androidplot.Plot.BorderStyle;
import com.androidplot.ui.SizeLayoutType;
import com.androidplot.ui.SizeMetrics;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;

import iha.auh.kds.aba.painratingapp.Models.ChildModel;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader.TileMode;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class GraduationLineActivity extends Activity {
	private XYPlot plot;

	private BroadcastReceiver dataReadyFromService = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equalsIgnoreCase(DataService.GET_PAIN_RATINGS)) {
				String response = intent.getExtras().getString("response");
				if (response.equalsIgnoreCase("success")) {
					doPlot();
				} else if (response.equalsIgnoreCase("failure")) {
					Toast.makeText(GraduationLineActivity.this, "Der skete en fejl :(",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	private void doPlot() {
		int arraySize = ChildSingleton.getChild().PainScoring.size();
		Number[] series0Numbers = new Number[arraySize];

		int numberOfPoints = 20;
		int startPosition = 0;
		if (arraySize > numberOfPoints)
			startPosition = arraySize - numberOfPoints;
		
		for (int i = startPosition; i < arraySize; i++) {
			series0Numbers[i] = ChildSingleton.getChild().PainScoring.get(i).PainRating;
		}

		// Turn the above arrays into XYSeries':
		XYSeries series1 = new SimpleXYSeries(
				Arrays.asList(series0Numbers), 
				SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, 
				"Series1");

		// Create a formatter to use for drawing a series using
		// LineAndPointRenderer:
		LineAndPointFormatter series1Format = new LineAndPointFormatter(
				Color.rgb(165, 222, 82), // line color Color.rgb(0, 200, 0)
				Color.rgb(125, 222, 82), // point color Color.rgb(0, 100, 0)
				Color.CYAN, null); // fill color

		// setup our line fill paint to be a slightly transparent gradient:
		Paint lineFill = new Paint();
		lineFill.setAlpha(200);
		lineFill.setShader(new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.rgb(170, 222, 82), TileMode.MIRROR));
		//lineFill.setShader(new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.GREEN, TileMode.MIRROR));

		series1Format.setFillPaint(lineFill);

		// add a new series' to the xyplot:
		plot.addSeries(series1, series1Format);
		plot.redraw();
	}

	private void styleGraph() {
		// Style found at: http://stackoverflow.com/questions/15450328/androidplot-background-and-ranges
		plot.setBorderStyle(BorderStyle.NONE, null, null);
		plot.setPlotMargins(0, 0, 0, 0);
		plot.setPlotPadding(0, 0, 0, 0);
		plot.setGridPadding(0, 10, 5, 0);

		plot.setBackgroundColor(Color.WHITE);

		plot.getGraphWidget().setSize(new SizeMetrics(
	            0, SizeLayoutType.FILL,
	            0, SizeLayoutType.FILL));

		plot.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE);
		plot.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);

		plot.getGraphWidget().getDomainLabelPaint().setColor(Color.BLACK);
		plot.getGraphWidget().getRangeLabelPaint().setColor(Color.BLACK);

		plot.getGraphWidget().getDomainOriginLabelPaint().setColor(Color.BLACK);
		plot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK);
		plot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK);

		// Domain
		//plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, days.length);
		plot.setDomainValueFormat(new DecimalFormat("0"));
		plot.setDomainStepValue(1);

		// Range
		plot.setRangeBoundaries(0, 10, BoundaryMode.FIXED);
		plot.setRangeStepValue(11);
		//plot.setRangeStep(XYStepMode.SUBDIVIDE, arraySize);
		plot.setRangeValueFormat(new DecimalFormat("0"));

		// Remove legend
		plot.getLayoutManager().remove(plot.getLegendWidget());
		plot.getLayoutManager().remove(plot.getDomainLabelWidget());
		plot.getLayoutManager().remove(plot.getRangeLabelWidget());
		plot.getLayoutManager().remove(plot.getTitleWidget());
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_graduation_line);

		ChildModel child = ChildSingleton.getChild();

		Intent serviceIntent = new Intent(this, DataService.class);
		String url = "http://painratingrestful.cloudapp.net/api/painrating/getchild?cpr="
				+ child.CPR;

		serviceIntent.putExtra("get_pain_ratings_url", url);
		startService(serviceIntent);

		plot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
		styleGraph();
	}

	@Override
	protected void onResume() {
		super.onResume();
		LocalBroadcastManager.getInstance(this).registerReceiver(
				dataReadyFromService,
				new IntentFilter(DataService.GET_PAIN_RATINGS));
	}

	@Override
	protected void onPause() {
		super.onPause();
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				dataReadyFromService);
	}

	public void finish(View view) {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
	}
	
	@Override
	public void onBackPressed() {
		// Should not be possible to go back from here
		Toast.makeText(this, "Disabled.. Sorry :(", Toast.LENGTH_SHORT).show();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.graduation_line, menu);
		return true;
	}

}
